package com.hz.ws.pay;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.hz.beans.user.entity.AlipayOrderEntity;
import com.hz.beans.user.entity.AlipayRefundEntity;
import com.hz.sys.config.AlPayConfig;
import com.hz.sys.utils.ResponseUtils;
import com.hz.utils.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.HashMap;
import java.util.Map;

/**
 * 创建人: mcz
 * 创建日期: 2018/11/1 13:36
 * 描述:  支付宝支付接口控制器
 * 版本: 1.0
 */
@Api(tags = "支付宝二维码支付")
@Controller
@RequestMapping("/api/pay")
public class AliPayController {
    private Logger logger=LoggerFactory.getLogger(AliPayController.class);
    //初始化客户端 只需要实例化一次（线程安全）
    private static  AlipayClient alipayClient = new DefaultAlipayClient(AlPayConfig.AL_GATEWAY, AlPayConfig.APP_ID, AlPayConfig.APP_PRIVATE_KEY, AlPayConfig.FOAMATE, AlPayConfig.CHARSET, AlPayConfig.ALI_PAY_PUBLIC_KEY, AlPayConfig.SIGN_TYPE);


    /**
     *  预下单请求，获取阿里二维码接口
     * @throws AlipayApiException
     * @Param out_trade_no 商户订单号,64个字符以内、只能包含字母、数字、下划线；需保证在商户端不重复
     * @Param total_amount 订单总金额，单位为元，精确到小数点后两位，取值范围[0.01,100000000] 如果同时传入了【打折金额】，【不可打折金额】，
     * 【订单总金额】三者，则必须满足如下条件：【订单总金额】=【打折金额】+【不可打折金额】
     * @Param subject 订单标题
     * @Param store_id 商户门店编号
     * @Param timeout_express 该笔订单允许的最晚付款时间，逾期将关闭交易。
     * 取值范围：1m～15d。m-分钟，h-小时，d-天，1c-当天（1c-当天的情况下，无论交易何时创建，都在0点关闭）。 该参数数值不接受小数点， 如 1.5h，可转换为 90m。
     */
    @ApiOperation(value = "二维码支付", notes = "支付宝二维码支付", httpMethod = "POST")
    @RequestMapping(value="/alipayTradePrecreate",method = {RequestMethod.POST})
    @ResponseBody
    public String alipayTradePrecreate(AlipayOrderEntity alipayOrder)  {
        //创建API对应的request类
        AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
        ResponseUtils responseUtils = new ResponseUtils();
        String res;
        //设置异步回调地址
        request.setNotifyUrl(alipayOrder.getNotifyUrl());
        //request.setReturnUrl(alipayOrder.getReturnUrl());
        if (StringUtil.isBlank(alipayOrder.getOutTradeNo())) {
            responseUtils.setResponseDesc("参数非法");
            return responseUtils.failJSON(responseUtils);
        }else{
            Map<String,Object> maps=new HashMap<>(10);
            maps.put("out_trade_no",alipayOrder.getOutTradeNo());
            maps.put("total_amount",alipayOrder.getTotalAmount());
            if(StringUtils.isNotBlank(alipayOrder.getSubject())){
                maps.put("subject",alipayOrder.getSubject());
            }
            if(StringUtils.isNotBlank(alipayOrder.getBody())){
                maps.put("body",alipayOrder.getBody());
            }
            if(StringUtils.isNotBlank(alipayOrder.getQrCodeTimeoutExpress())){
                maps.put("qr_code_timeout_express",alipayOrder.getQrCodeTimeoutExpress());
            }
            if(StringUtils.isNotBlank(alipayOrder.getTimeoutExpress())){
                maps.put("timeout_express",alipayOrder.getTimeoutExpress());
            }
            //把订单信息转换为json对象的字符串
            String postdata = JSONObject.fromObject(maps).toString();
            request.setBizContent(postdata);
            try {
                AlipayTradePrecreateResponse response = alipayClient.execute(request);
                if( "10000".equals(response.getCode())){
                    responseUtils.setResponseData(response.getQrCode());
                    responseUtils.setResponseDesc("获取支付宝二维码成功");
                    res=responseUtils.successJSON(responseUtils);
                }else{
                    String body = response.getBody();
                    JSONObject jsonObject = JSONObject.fromObject(body);
                    String sub_msg = jsonObject.getJSONObject("alipay_trade_precreate_response").getString("sub_msg");
                    responseUtils.setResponseDesc(sub_msg);
                    res=responseUtils.failJSON(responseUtils);
                }
            } catch (Exception e) {
                logger.error("调用支付宝二维码接口异常{}",e);
                responseUtils.setResponseDesc("获取支付宝二维码异常");
                res=responseUtils.failJSON(responseUtils);
            }
        }
        return res;
    }


     /**
      * @Author mcz
      * @Description  支付宝交易订单状态查询
      * @Date 2018/11/6 10:03
      * @Param out_trade_no    String	特殊可选	64	订单支付时传入的商户订单号,和支付宝交易号不能同时为空。
      *         trade_no,out_trade_no如果同时存在优先取trade_no	20150320010101001
      *  @Param       trade_no	String	特殊可选	64	支付宝交易号，和商户订单号不能同时为空
      * @return String
      **/
     @ApiOperation(value = "支付宝交易订单状态查询", notes = "支付宝交易订单状态查询", httpMethod = "POST")
     @RequestMapping(value = "queryAliPayStatus",method = {RequestMethod.POST,RequestMethod.GET})
     @ResponseBody
    public String queryAliPayStatus(String outTradeNo,String tradeNo){
        ResponseUtils responseUtils=new ResponseUtils();
        String result;
        if(StringUtils.isBlank(outTradeNo)&&StringUtils.isBlank(tradeNo)){
            responseUtils.setResultFlag(false);
            responseUtils.setResponseDesc("参数不能同时为空");
            result=responseUtils.failJSON(responseUtils);
        }else{
            AlipayTradeQueryRequest alipayTradeQueryRequest=new AlipayTradeQueryRequest();
            Map<String,Object> alipayTradeQueryModel=new HashMap<>(3);
            if(StringUtils.isNotBlank(outTradeNo)){
                alipayTradeQueryModel.put("out_trade_no",outTradeNo);
            }
            if(StringUtils.isNotBlank(tradeNo)){
                alipayTradeQueryModel.put("trade_no",tradeNo);
            }
            alipayTradeQueryRequest.setBizContent(JSON.toJSONString(alipayTradeQueryModel));
            try {
                AlipayTradeQueryResponse alipayTradeQueryResponse=alipayClient.execute(alipayTradeQueryRequest);
                if(("10000").equals(alipayTradeQueryResponse.getCode())){
                    responseUtils.setResponseDesc("查询成功");
                    responseUtils.setResponseData(alipayTradeQueryResponse.getTradeStatus());
                    result=responseUtils.successJSON(responseUtils);
                }else{
                    responseUtils.setResponseDesc("查询失败");
                    responseUtils.setResponseData(alipayTradeQueryResponse.getTradeStatus());
                    result=responseUtils.failJSON(responseUtils);
                }
            } catch (AlipayApiException e) {
                logger.error("交易查询异常{}",e);
                responseUtils.setResponseDesc("查询异常");
                responseUtils.setResponseData(e.getErrMsg()+e.getErrCode());
                result=responseUtils.failJSON(responseUtils);
            }
        }
        return result;
    }

     /**
      * @Author mcz
      * @Description   支付宝退款接口
      * @Date 2018/11/7 17:32
      * @Param 
      * @return 
      **/
     @ApiOperation(value = "支付宝退款接口", notes = "支付宝退款接口", httpMethod = "POST")
     @RequestMapping(value = "alipayTradeRefund",method = {RequestMethod.POST,RequestMethod.GET})
     @ResponseBody
     public String alipayTradeRefund(AlipayRefundEntity alipayRefundEntity){
         ResponseUtils responseUtils=new ResponseUtils();
         String res;
         Map<String,String> refondMap=new HashMap<>(6);
         if(!StringUtil.isNotBlank(alipayRefundEntity.getOrderNo())||!StringUtil.isNotBlank(alipayRefundEntity.getTradeNo())){
             responseUtils.setResult("订单号和阿里交易号不能同时为空");
             return responseUtils.failJSON(responseUtils);
         }
         if(!StringUtil.isNotBlank(alipayRefundEntity.getRefundAmount())){
             responseUtils.setResult("退款金额不能为空");
             return responseUtils.failJSON(responseUtils);
         }
         if(StringUtil.isNotBlank(alipayRefundEntity.getOrderNo())){
             refondMap.put("out_trade_no",alipayRefundEntity.getOrderNo());
         }
         if(StringUtil.isNotBlank(alipayRefundEntity.getTradeNo())){
             refondMap.put("trade_no",alipayRefundEntity.getTradeNo());
         }
         if(StringUtil.isNotBlank(alipayRefundEntity.getRefundAmount())){
             refondMap.put("refund_amount",alipayRefundEntity.getRefundAmount());
         }
         if(StringUtil.isNotBlank(alipayRefundEntity.getReFundReason())){
             refondMap.put("refund_reason",alipayRefundEntity.getReFundReason());
         }
         AlipayTradeRefundRequest alipayTradeRefundRequest=new AlipayTradeRefundRequest();
         alipayTradeRefundRequest.setBizContent(JSON.toJSONString(alipayRefundEntity));
         try {
             AlipayTradeRefundResponse alipayTradeRefundResponse=alipayClient.execute(alipayTradeRefundRequest);
             if("10000".equalsIgnoreCase(alipayTradeRefundResponse.getCode())){
                responseUtils.setResult("退款成功");
                responseUtils.setResponseData(alipayTradeRefundResponse.getOutTradeNo());
                res=responseUtils.successJSON(responseUtils);
             }else{
                 responseUtils.setResult("退款失败");
                 responseUtils.setResponseData(alipayTradeRefundResponse.getSubMsg());
                 res=responseUtils.failJSON(responseUtils);
             }
         } catch (AlipayApiException e) {
             responseUtils.setResult("交易退款异常");
             res=responseUtils.failJSON(responseUtils);
             logger.error("退款异常{}",e);
         }
         return res;
    }





























   /* @RequestMapping(value="/alipayTradePrecreate",method = {RequestMethod.POST})
    @ResponseBody
    public String alipayTradePrecreate(String orderId,String money)  {
        //创建API对应的request类
        AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
        ResponseUtils responseUtils = new ResponseUtils();
        String res=null;
        //设置回调地址
        request.setNotifyUrl("http://www.andata.com.cn/aliPayCallBack.do");
        if (orderId!=null&&orderId.isEmpty()&&money!=null&&money.isEmpty()) {
            responseUtils.setResponseDesc("参数非法");
            return responseUtils.failJSON(responseUtils);
        }else{
            Map<String,Object> maps=new HashMap<>(9);
            maps.put("out_trade_no","987469");
            maps.put("total_amount","0.01");
            maps.put("subject","小编机器人纠错");
            maps.put("store_id","XB00103");
            maps.put("timeout_express","3m");
            //根据订单号查询订单信息
            //ProductOrders productOrders = this.proOrdersService.selectByOrderId(orderid);
            //把订单信息转换为json对象的字符串
            String postdata = JSONObject.fromObject(maps).toString();
            request.setBizContent(postdata);
            try {
                AlipayTradePrecreateResponse response = alipayClient.execute(request);
                if( "10000".equals(response.getCode())){
                    responseUtils.setResponseData(response.getQrCode());
                    responseUtils.setResponseDesc("获取支付宝二维码成功");
                    res=responseUtils.successJSON(responseUtils);
                }else{
                    String body = response.getBody();
                    JSONObject jsonObject = JSONObject.fromObject(body);
                    String sub_msg = jsonObject.getJSONObject("alipay_trade_precreate_response").getString("sub_msg");
                    responseUtils.setResponseDesc(sub_msg);
                    res=responseUtils.failJSON(responseUtils);
                }
                //String body = response.getBody();
                //JSONObject jsonObject = JSONObject.fromObject(body);sub_msg
                //String qr_code = jsonObject.getJSONObject("alipay_trade_precreate_response").getString("qr_code");
                //流输出
                //ServletOutputStream sos;
                //sos = responses.getOutputStream();
                //生成二维码
                //QRCodeUtil.encode(qr_code, sos);
            } catch (Exception e) {
                logger.error("调用支付宝二维码接口异常{}",e);
                responseUtils.setResponseDesc("获取支付宝二维码异常");
                res=responseUtils.failJSON(responseUtils);
            }
        }
        return res;
    }

*/


}
